package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constans.message.ArticleForEsConstants;
import com.heima.common.constans.message.NewsAutoScanConstants;
import com.heima.common.constans.wemedia.WemediaContans;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.dtos.WmNewsDto;
import com.heima.model.media.dtos.WmNewsPageReqDto;
import com.heima.model.media.pojos.WmMaterial;
import com.heima.model.media.pojos.WmNews;
import com.heima.model.media.pojos.WmNewsMaterial;
import com.heima.model.media.pojos.WmUser;
import com.heima.search.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${fdfs.url}")
    private String fileServerUrl;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    @Override
    public ResponseResult findList(WmNewsPageReqDto wmNewsPageReqDto) {
        if (wmNewsPageReqDto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"请登陆后在尝试");
        }
        Page<WmNews>page = new Page<>(wmNewsPageReqDto.getPage(),wmNewsPageReqDto.getSize());

        LambdaQueryWrapper<WmNews> queryWrapper = Wrappers.<WmNews>lambdaQuery();
        if (wmNewsPageReqDto.getStatus()!=null){
            queryWrapper.eq(WmNews::getStatus,wmNewsPageReqDto.getStatus());
        }
        if (wmNewsPageReqDto.getChannelId()!=null){
            queryWrapper.eq(WmNews::getChannelId,wmNewsPageReqDto.getChannelId());
        }
        if ( StringUtils.isNotBlank(wmNewsPageReqDto.getKeyword())){
            queryWrapper.like(WmNews::getTitle,wmNewsPageReqDto.getKeyword());
        }
        if (wmNewsPageReqDto.getBeginPubDate()!=null){
            queryWrapper.ge(WmNews::getPublishTime,wmNewsPageReqDto.getBeginPubDate());
        }
        if (wmNewsPageReqDto.getEndPubDate()!=null){
            queryWrapper.le(WmNews::getPublishTime,wmNewsPageReqDto.getEndPubDate());
        }
        queryWrapper.eq(WmNews::getUserId,user.getId());
        queryWrapper.orderByDesc(WmNews::getPublishTime);
        IPage<WmNews> wmNewsIPage = this.page(page, queryWrapper);
        ResponseResult responseResult = new PageResponseResult(wmNewsPageReqDto.getPage(),wmNewsPageReqDto.getSize(),wmNewsIPage.getTotal());
        responseResult.setData(wmNewsIPage.getRecords());
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    @Override
    public ResponseResult saveNews(WmNewsDto dto) {
        if (dto==null||StringUtils.isEmpty(dto.getContent())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getStatus()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"登陆后再试");
        }
        WmNews wmNews = new WmNews();

            BeanUtils.copyProperties(dto,wmNews);
            if (wmNews.getType()==-1){
                wmNews.setType(null);
            }

        List<String> images = dto.getImages();
            if (images!=null&&images.size()!=0){
                List<String> collect = images.stream().map(image -> image.replace(fileServerUrl, "")).collect(Collectors.toList());
                String imageUrl = StringUtils.join(collect, ",");
                wmNews.setImages(imageUrl);
            }

            wmNews.setUserId(user.getId());
            saveOrUpdateWmNews(wmNews);

        String content = dto.getContent();
        List<Map> maps = JSONArray.parseArray(content, Map.class);
        List<String>contentImages=new ArrayList<>();
        if (maps!=null){
            for (Map map : maps) {
                String type = (String) map.get("type");
                if (WemediaContans.WM_NEWS_TYPE_IMAGE.equals(type)){
                    contentImages.add(((String) map.get("value")).replace(fileServerUrl,""));
                }
            }
        }

        if(!WmNews.Status.NORMAL.getCode().equals(dto.getStatus())&& contentImages!=null && !contentImages.isEmpty()){
            saveRelativeInfo(contentImages,wmNews.getId(),WemediaContans.WM_CONTENT_REFERENCE);
        }
        if(contentImages!=null&&!contentImages.isEmpty()&&WemediaContans.WM_NEWS_TYPE_AUTO.equals(dto.getType())){
            images  =   autoSetCoverImages(wmNews,contentImages);
        }
        if (images!=null&&!images.isEmpty()&&!WmNews.Status.NORMAL.getCode().equals(dto.getStatus())){
            saveRelativeInfo(images,wmNews.getId(),WemediaContans.WM_COVER_REFERENCE);
        }



        kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC, JSON.toJSONString(wmNews.getId()));

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult findWmNewsById(Integer id) {
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章Id不可缺少");
        }
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNews);
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    @Override
    public ResponseResult delNews(Integer id) {
        if(id == null){
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = this.getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if(wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode()) && wmNews.getEnable()==1){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布，不能删除");
        }
        this.removeById(wmNews.getId());
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        if (dto==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Integer id = dto.getId();
        WmNews wmNews = this.getById(id);
        if (wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if(!WmNews.Status.PUBLISHED.getCode().equals(wmNews.getStatus())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不是发布状态，不能上下架");
        }
        if(dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2){
           Boolean update= update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId()).set(WmNews::getEnable,dto.getEnable()));
            if (update&&wmNews.getArticleId()!=null){
                Map map = new HashMap();
                Short enable = dto.getEnable();
                map.put("enable",enable);
                map.put("articleId",wmNews.getArticleId());
                //是否上架  0 下架  1 上架
                if(enable == 0){
                    kafkaTemplate.send(ArticleForEsConstants.ARTICLE_ELASTICSEARCH_DELETE,wmNews.getArticleId().toString());
                }else {
                    kafkaTemplate.send(ArticleForEsConstants.ARTICLE_ELASTICSEARCH_ADD,wmNews.getArticleId().toString());
                }
            }
        }


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }


    private List<String> autoSetCoverImages(WmNews wmNews,List<String>contentImages){
        List<String> images = new ArrayList<>();
        if (contentImages.size()>2){
            wmNews.setType(WemediaContans.WM_NEWS_MANY_IMAGE);
            images = contentImages.stream().limit(3).collect(Collectors.toList());
        }else if (contentImages.size()>0&&contentImages.size()<=2){
            wmNews.setType(WemediaContans.WM_NEWS_SINGLE_IMAGE);
            images = contentImages.stream().limit(1).collect(Collectors.toList());
        }else {
            wmNews.setType(WemediaContans.WM_NEWS_NONE_IMAGE);
        }
        if (images!=null){
            wmNews.setImages(StringUtils.join(images,","));

        }
        this.updateById(wmNews);
        return images;
    }

    private void saveRelativeInfo(List<String> imageList, Integer newsId, Short type){
        List<String> collect = imageList.stream().map(image -> image.replace(fileServerUrl, "")).collect(Collectors.toList());
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(
                Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, collect)
                        .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId())
        );
        if (wmMaterials==null){
            throw new CustomException(ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR));
        }
        Map<String, Integer> wmMaterialMaps = wmMaterials.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
        List<Integer> ids =new ArrayList<>();
        for (String url : collect) {
            Integer id = wmMaterialMaps.get(url);
            if (!wmMaterialMaps.containsKey(url)){
                throw new CustomException(ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR));
            }
            ids.add(id);
        }
        WmNewsMaterial material = new WmNewsMaterial();


        for (int i = 0; i < ids.size(); i++) {
            material.setMaterialId(ids.get(i));
            material.setNewsId(newsId);
            material.setType(type);
            material.setOrd((short)i);
            wmNewsMaterialMapper.insert(material);
        }
    }

    private void saveOrUpdateWmNews(WmNews wmNews) {
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short)1); // 上架
        if(wmNews.getId()==null){
            save(wmNews);
        }else {
            wmNewsMaterialMapper.delete(
                    Wrappers.<WmNewsMaterial>lambdaQuery()
                            .eq(WmNewsMaterial::getNewsId,wmNews.getId())
            );
            updateById(wmNews);
        }
    }
}
